package com.infore.dataReceiving.core.filter.instructions;
import com.infore.dataReceiving.core.chain.Water2018InstructionsChain;
import com.infore.dataReceiving.core.enums.Water2018InstructionsTypeEnum;
import com.infore.dataReceiving.core.filter.Water2018InstructionsFilter;
import com.infore.dataReceiving.dto.WaterInstructionsDto;
import com.infore.dataReceiving.repository.IBackControlLogRepository;
import com.infore.dataReceiving.util.CRCCheck;
import com.infore.dataReceiving.util.Water2018InstructionsHandleUtil;
import com.infore.dataReceiving.util.RedisUtil;

import io.netty.channel.ChannelHandlerContext;

/**
 * 心跳包
 * @author 69457
 *
 */
public class HeartbeatFilter  implements Water2018InstructionsFilter{
	
	@Override
	public void doFilter(ChannelHandlerContext ctx,WaterInstructionsDto dto,
			Water2018InstructionsChain chain,RedisUtil redisUtil,IBackControlLogRepository repository, boolean interrupt) {
		if(Water2018InstructionsTypeEnum.water2018_9015.getCn().equals(dto.getCn())) {
			interrupt = true;
			String iflag = Integer.toBinaryString(dto.getFlag());
			String isAnswer = iflag.substring(iflag.length()-1);
			if("1".equals(isAnswer)) {
				System.out.println("正在回复心跳包消息！！！！！！！！！！！！！");
				String mn = dto.getMn();
				String qn = dto.getQn();
				String pw = dto.getPw();
				String datas = "QN="+qn+";ST=91;CN=9014;PW="+pw+";MN="+mn+";CP=&&QnRtn=1&&";
				int dataLength = datas.length();//数据段长度
				String crcCheck = CRCCheck.crc16(datas, dataLength);
				String dataLengthString = Water2018InstructionsHandleUtil.getDataLengthString(dataLength+"");
				String returnInfo = "##"+dataLengthString+datas+crcCheck+"\r\n";
				ctx.channel().writeAndFlush(returnInfo);
			}
		}
		chain.doFilter(ctx,dto,chain,redisUtil,repository,interrupt);
	}

}
